package com.ayf.payment.game.api.controller.paychannel;

import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.channel.jiabei.util.JbStringUtil;
import com.ayf.payment.game.api.channel.jiabei.util.StringHelper;
import com.ayf.payment.game.api.dto.platform.SubstitutePayConfigDTO;
import com.ayf.payment.game.api.dto.platform.pay.WanXiangPayConfigParamVO;
import com.ayf.payment.game.api.entity.Order;
import com.ayf.payment.game.api.type.OrderStatus;
import com.ayf.payment.game.api.utils.MD5Util;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.ayf.payment.game.api.wx.WxSendMsgUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import com.swwx.charm.zookeeper.exception.GetLockFailedException;
import com.swwx.charm.zookeeper.exception.ReleaseLockFailedException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.text.MessageFormat;

/**
 * 万象
 *
 * @author wwl
 * @description:
 * @date 2020/5/13 14:34
 */
@RequestMapping("/v/wanx/pay")
@RestController
public class WANXPayNotifyController extends BasePayNotifyController {
    @Autowired
    private WxSendMsgUtils wxSendMsgUtils;

    @RequestMapping("/notify")
    public void notify(HttpServletRequest request, HttpServletResponse response) {
        String orderno = JbStringUtil.formatString(request.getParameter("orderno"));
        super.notifyAsync(request,response,orderno);
    }

    /**
     * 代付异步通知处理
     */
    @RequestMapping("/paynotify")
    public void payNotify(HttpServletRequest request, HttpServletResponse response) {
        String orderno = JbStringUtil.formatString(request.getParameter("orderno"));
        super.agentPayNotifyAsync(request,response,orderno);
    }

    private String getOrderPaySign(String status, String parter, String orderno, String amount,String servicecharge, String key) {
        String format = "version={0}&status={1}&parter={2}&orderno={3}&amount={4}&servicecharge={5}&key={6}";
        String sign = MessageFormat.format(format, "2.1", status, parter, orderno, amount, servicecharge, key);
        String md5 = MD5Util.strToMd5(sign);
        if (StringUtils.isEmpty(md5)) {
            return null;
        }
        return md5.toLowerCase();
    }

    @RequestMapping("/returns")
    public void returns(HttpServletRequest request, HttpServletResponse response) {
        String orderno = JbStringUtil.formatString(request.getParameter("orderno"));
        super.notifySync(request,response,orderno);
    }

    @Override
    protected void notifyAsyncBusinesExec(HttpServletRequest request, HttpServletResponse response,Object obj) {
        PrintWriter pw = null;
        String traceId = SnowFlakeUtils.getTraceId();
        try {
            pw = response.getWriter();
            //获取参数
            String version = JbStringUtil.formatString(request.getParameter("version"));
            String status = JbStringUtil.formatString(request.getParameter("status"));
            String parter = JbStringUtil.formatString(request.getParameter("parter"));
            String orderno = JbStringUtil.formatString(request.getParameter("orderno"));
            String orderid = JbStringUtil.formatString(request.getParameter("orderid"));
            String amount = JbStringUtil.formatString(request.getParameter("amount"));
            String sign = JbStringUtil.formatString(request.getParameter("sign"));
            LogPortal.info("{} 万象交易异步通知 参数：version[{}] status[{}] parter[{}] orderno[{}] orderid[{}] amount[{}] sign[{}]", traceId, version, status, parter, orderno, orderno, amount, sign);
            if (StringUtils.isEmpty(orderno)) {
                LogPortal.info("{} 万象交易异步通知 订单号数值为空，不进行后续操作", traceId);
                return;
            }
            Order order = orderService.selectByMerchantOrderNo(orderno);
            if (order == null) {
                LogPortal.error("{} 万象交易异步通知 订单号[{}]在我方系统查询不到", traceId, orderno);
                return;
            }
            String KeyValue = systemInitialization.channelDTO(order.getPayChannleId()).getChannelKey();
            //生成签名
            StringBuffer dicStr = new StringBuffer();
            dicStr.append("version=").append(version);
            dicStr.append("&status=").append(status);
            dicStr.append("&parter=").append(parter);
            dicStr.append("&orderno=").append(orderno);
            dicStr.append("&amount=").append(amount);
            dicStr.append("&key=").append(KeyValue);
            String signVer = StringHelper.EncodeMD5(dicStr.toString());
            signVer = signVer.toLowerCase();
            OrderStatus orderStatus = OrderStatus.PROCESSING;
            LogPortal.debug("{} 万象交易异步通知 签名原文：{} signVER: {}--{}", traceId, dicStr.toString(), signVer, sign);
            if (sign.trim().equals(signVer.trim())) {
                if ("fail".equals(status)) {
                    orderStatus = OrderStatus.FAIL;
                    order.setScriptStatus(-1);
                } else if ("success".equals(status)) {
                    orderStatus = OrderStatus.SUCCESS;
                }
                if (OrderStatus.PROCESSING.equals(order.getOrderStatus())) {
                    String XY_GAME_PAY_LOCK_FLAG= System.getenv("XY_GAME_PAY_LOCK_FLAG");
                    String orderLockName = "orderLock".concat(this.getClass().getSimpleName()).concat(XY_GAME_PAY_LOCK_FLAG).concat(orderno);
                    boolean orderLock=false;
                    try {
                        if (orderLock = distributedLock.getLock(orderLockName)) {
                            Order order2 = orderService.selectByMerchantOrderNo(orderno);
                            if (order2 != null && OrderStatus.PROCESSING.equals(order2.getOrderStatus())){
                                order.setOrderNo(orderid);
                                order.setOrderStatus(orderStatus);
                                orderService.paymentOrder(order, new JSONObject());
                                if (OrderStatus.SUCCESS.equals(order.getOrderStatus())) {
                                    orderService.orderToGetWay(order);
                                    try {
                                        wxSendMsgUtils.rechargeSuccess(order);
                                    } catch (Exception e) {
                                        LogPortal.error("{} 万象交易异步通知 商户订单号[{}]CallBack 微信通知异常", e, traceId, orderno);
                                    }
                                }
                            }
                        }
                    } catch (GetLockFailedException e) {
                        LogPortal.error("{} >>> [DISTRIBUTED_LOCK_ACQUIRE_FAILED_ZK] 分布式锁获取失败,锁名称为:{}", orderno, orderLockName);
                        LogPortal.error("{} >>> {} 获取lock失败", e, orderno, orderLockName);
                    } catch (Exception e) {
                        LogPortal.error("{} >>> {} 任务执行出错 ", e, orderno, orderLockName);
                    } finally {
                        if (orderLock) {
                            LogPortal.info(orderno + " >>> " + orderLockName + " finished.");
                            try {
                                distributedLock.releaseLock(orderLockName);
                            } catch (ReleaseLockFailedException e) {
                                LogPortal.error("{} >>> [DISTRIBUTED_LOCK_RELEASE_FAILED_ZK] 分布式锁释放失败,锁名称为:{}",orderno, orderLockName);
                                LogPortal.error("{} >>> {} 释放失败", e, orderid, orderLockName);
                            }
                        }
                    }
                } else {
                    LogPortal.info("{} 万象交易异步通知 商户订单号[{}] 异步通知 不在更新订单状态：[{}]", traceId, orderno, order.getOrderStatus());
                }
            } else {
                LogPortal.error("{} 万象交易异步通知 商户订单号[{}] 异步通知验签失败", traceId, orderno);
            }
        } catch (Exception e) {
            LogPortal.error("{} 万象交易异步通知 验签业务逻辑处理失败，具体原因:{}", e, traceId, e.getMessage());
        } finally {
            pw.write("ok");
            pw.flush();
            if (pw != null)
                pw.close();
        }
    }

    @Override
    protected void notifySyncBusinesExec(HttpServletRequest request, HttpServletResponse response) {
        String orderno = JbStringUtil.formatString(request.getParameter("orderno"));
        try {
            String remark = JbStringUtil.formatString(request.getParameter("remark"));
            response.sendRedirect(remark+"/gws/loading.html?orderNo=" + orderno);
        } catch (Exception e) {
            LogPortal.error("万象交易同步通知 商户订单号[{}] 发生{}异常",e,orderno,e.getClass().getName());
        }
    }

    @Override
    protected void agentPayNotifyAsyncBusinesExec(HttpServletRequest request, HttpServletResponse response, Object obj) {
        String version = JbStringUtil.formatString(request.getParameter("version"));
        String status = JbStringUtil.formatString(request.getParameter("status"));
        String parter = JbStringUtil.formatString(request.getParameter("parter"));
        String orderno = JbStringUtil.formatString(request.getParameter("orderno"));
        String amount = JbStringUtil.formatString(request.getParameter("amount"));
        String servicecharge = JbStringUtil.formatString(request.getParameter("servicecharge"));
        String addtime = JbStringUtil.formatString(request.getParameter("addtime"));
        String paytime = JbStringUtil.formatString(request.getParameter("paytime"));
        String sign = JbStringUtil.formatString(request.getParameter("sign"));
        String traceId = SnowFlakeUtils.getTraceId();
        LogPortal.info("{} 万象代付异步通知 参数：version[{}] status[{}] parter[{}] orderno[{}] amount[{}] servicecharge[{}] addtime[{}] paytime[{}] sign[{}]", traceId, version, status, parter, orderno, amount, servicecharge, addtime, paytime, sign);
        SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(4);
        WanXiangPayConfigParamVO wanXiangPayConfigParamVO = substitutePayConfigDTO.getWanXiangPayConfigParamVO();
        String orderPaySign = getOrderPaySign(status, wanXiangPayConfigParamVO.getParter(), orderno, amount, servicecharge, wanXiangPayConfigParamVO.getKey());
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            if (StringUtils.isBlank(sign)) {
                LogPortal.error("{} 万象代付异步通知 内容格式错误",traceId);
                pw.write("fail");
                pw.flush();
                return;
            }
            if (!sign.equals(orderPaySign)) {
                LogPortal.error("{} 万象代付异步通知 验签失败 渠道签名[{}] 系统签名[{}]", traceId, sign, orderPaySign);
                pw.write("fail");
                pw.flush();
                return;
            }
            if (StringUtils.isEmpty(orderno)) {
                LogPortal.info("{} 万象代付异步通知 商户订单号数值为空，不进行后续操作", traceId);
                pw.write("fail");
                pw.flush();
                return;
            }
            if (orderno.startsWith("Y")) {
                merchantCashOutService.WanXPaymentOnBehalfOf(traceId, status, orderno);
            } else {
                merchantPayOrderService.WanXPayNotify(traceId, status, orderno);
            }
            pw.write("ok");
            pw.flush();
        } catch (Exception e) {
            LogPortal.error("{} 万象代付异步通知 业务逻辑处理失败，具体原因:{}", e, traceId, e.getMessage());
            pw.write("万象代付异步通知响应验签处理失败：" + e.getMessage());
            pw.flush();
        } finally {
            if (pw != null)
                pw.close();
        }
    }
}
